package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import persistence.Axdbv4HibernateManager;
import domain.RepresentationsNamesRecord;

public class SetAsMasterServlet extends HttpServlet{

	/**
	 *  Servlet invocata al momento della selezione di un 
	 *  nuovo master (tra sinonimi suggeriti)
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html; charset=UTF-8");
		this.doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html; charset=UTF-8");
		long oldMasterNID=Long.valueOf((String) req.getParameter("oldMasterNID"));
		long newMasterNID=Long.valueOf((String)req.getParameter("newMasterNID"));
		
		System.out.println("Avviata SetAsMasterServlet oldMaster:"+oldMasterNID+" nuovoMaster:"+newMasterNID);
		//Deve: 
		//	1. Prendere tutti i sinonimi associati a "oldMasterNID" e 
		//	  settargli come representativeNID il valore "newMasterNID"
		//	2. Settare  al record indivuato da "oldMasterNID" il
		// 	  representativeNID uguale a newMasterNID
		//	3. Settare representativeNID=-1 al record con NID uguale a "newMasterNID"
		
		Axdbv4HibernateManager dbManager=Axdbv4HibernateManager.getIstance();
		//1
		System.out.println("\tPer tutti i sinonimi di "+ oldMasterNID+" setto il nuovo representative "+newMasterNID);
		for (RepresentationsNamesRecord r : dbManager.getSynonymous(oldMasterNID)) {
			dbManager.updateRepresentationName(r.getNID(),newMasterNID);
			System.out.println("\t\tA "+r.getValue()+"("+r.getNID()+") associo il nuovo master "+newMasterNID);
		}
		//2
		dbManager.updateRepresentationName(oldMasterNID, newMasterNID);
		//3
		dbManager.updateRepresentationName(newMasterNID, -1);
	}
}
